package main

import (
	"log"
	"os"
	"os/exec"
	"strings"
	"path/filepath"
	"errors"
	."spideramazon/modules"
)
/// CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build
/// CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build
func main() {
	// 初始化文件夹
	currentPath, err := getCurrentPath()
	if err != nil {
		log.Panic(err)
	}

	// 创建工作目录文件夹
	errstatus := initDir(currentPath+"/downloads/errojans")
	if errstatus == false {
		log.Panic("当前工作目录("+currentPath+")下创建downloads/errjans文件夹失败")
	} else {
		DownloadJanPath = currentPath+"/downloads/"
		ErrorJanPath    = currentPath+"/downloads/errojans/"
		log.Println("当前工作目录("+currentPath+")下创建downloads/errojans文件夹成功")
	}

	// 开启Http服务
	log.Println("Http服务器已启动...")
	router := initRouter()
	router.Run(":6666")
}

func initDir(pathList string) bool {
	err := os.MkdirAll(pathList, 0777)
	if err!=nil{
		return false
	} else {
		return true
	}
}

func getCurrentPath() (string, error) {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return "", err
	}
	path, err := filepath.Abs(file)
	if err != nil {
		return "", err
	}
	i := strings.LastIndex(path, "/")
	if i < 0 {
		i = strings.LastIndex(path, "\\")
	}
	if i < 0 {
		return "", errors.New(`error: Can't find "/" or "\".`)
	}
	return string(path[0 : i+1]), nil
}